<?php
header("Content-Type:text/html;charset=utf-8");
require("inc/common.inc.php");
$wxmxopenid = $_COOKIE["mxadminwx"]["wxmxopenid"];
$result['error']="";
//判断用户是否登录
if (trim($wxmxopenid)==""){
    $result['error'] = "不符合优惠券领取条件，请先关注我们的公众平台";
}

$vpp_user_info=$db->getinfo("select * from mx_user where weixinid='$wxmxopenid' limit 1");
if (!is_array($vpp_user_info) and $result['error']==""){
    $result['error'] = "非法用户，不能领取优惠券";
}

$id=intval($id);
if($id=="" and $result['error']==""){
    $result['error'] = "请先选择要领取的优惠券";
}
$sqlsel="select *  from mx_vpp_youhuiquan where id='$id' and isok='1' and isdelete='0' limit 1";
$newsdb=$db->getinfo($sqlsel);
if (!is_array($newsdb) and $result['error']==""){
    $result['error'] = "没有要领取的优惠券";
}

//判断优惠券有效期
if (date("Y-m-d")>$newsdb["enddate"] and $result['error']==""){
    $result['error'] = "此优惠券已经超过使用期，不能领取";
}
//判断已领取数量
$zhavenow=$db->getinfo("select count(num) as num from mx_vpp_lingqu_yhq where yhqid='$id' and userid='$vpp_user_info[id]' ");
if ($zhavenow["num"]>=$newsdb["num"] and $result['error']==""){
    $result['error'] = "此优惠券全部领取完了";
}
$havenow=$db->getinfo("select count(num) as num from mx_vpp_lingqu_yhq where yhqid='$id' and userid='$vpp_user_info[id]' ");
if ($havenow["num"]>=$newsdb["usernum"] and $result['error']==""){
    $result['error'] = "此优惠券每位会员最多领取{$newsdb[usernum]}张，不能再领取此优惠券";
}
if($result['error']==""){
	//领取优惠券
	$yhqcode=date("YmdHis").rand(1000,9999);
	//判断优惠券号是否存在
	$yhqhave=$db->getinfo("select * from mx_vpp_lingqu_yhq where yhqcode='$yhqcode' ");
	if (is_array($yhqhave)){
		$result['error'] = "优惠券加载失败，请重新点击领取";
	}
	$files=array(
		"yhqcode"    =>$yhqcode,
		"yhqid"      =>$newsdb["id"],
		"yhqname"    =>$newsdb["name"],
		"startdate"  =>$newsdb["startdate"],
		"enddate"    =>$newsdb["enddate"],
		"userid"     =>$vpp_user_info["id"],
		"num"        =>1,
		"createdate" =>date("Y-m-d H:i:s"),
	);
	$db->exe_insert("mx_vpp_lingqu_yhq",$files);
	if ($result['error']==""){$result['error']=0;}
}
echo json_encode($result); 
?>














